package com.hz.friends.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.security.auth.callback.Callback;

import com.androidquery.AQuery;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.serverrequest.ALUserEngine;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.MLog;

public class SendGiftActivity extends BaseActivity {
	private FrameLayout layout_alert;
	private ImageView imageview_alert;
	private ImageButton imbtn_bar_left;
	private AQuery aq;
	private GridView gridview;
	private List<AVUser> userlist = null;
	private final String TAG = "SendGiftActivity";
	private TextView txv_giftname;
	private TextView txv_giftprice;
	private Spinner spn_contacts;
	private EditText edt_giftnum;
	private EditText edt_message;
	private int itemgiftindex = 0;
	private Button btn_bar_righ;
	private GiftAdpter madpter;
	private TextView txv_wallet;
	private double wallet = 0;
	private AVUser user = null;
	private TextView txv_sendto;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sendgift);
		init();
		initViews();
		initEvents();
		uploadGiftlist();
		uploadUserList();
	}

	@Override
	protected void init() {
		aq = new AQuery(this);
		user = ((CustomApplication) getApplication()).user;
	}

	@Override
	protected void initViews() {
		imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		btn_bar_righ = (Button) findViewById(R.id.btn_bar_righ);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_right.setVisibility(View.INVISIBLE);
		// btn_bar_righ.setVisibility(View.VISIBLE);
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_title.setText("Send Gift");
		imbtn_bar_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (layout_alert.getVisibility() == View.VISIBLE) {
					closeAlert();
					return;
				}
				finish();
			}
		});

		gridview = (GridView) findViewById(R.id.gridview);
		txv_wallet = (TextView) findViewById(R.id.txv_wallet);
		
		layout_alert = (FrameLayout) findViewById(R.id.layout_alert);
		imageview_alert = (ImageView) findViewById(R.id.imageview_alert);
		txv_giftname = (TextView) layout_alert.findViewById(R.id.txv_name);
		txv_giftprice = (TextView) layout_alert.findViewById(R.id.txv_price);
		spn_contacts = (Spinner) layout_alert.findViewById(R.id.spn_contacts);
		txv_sendto = (TextView) layout_alert.findViewById(R.id.txv_sendto);
		edt_giftnum = (EditText) layout_alert.findViewById(R.id.edt_num);
		edt_message = (EditText) layout_alert.findViewById(R.id.edt_message);
		spn_contacts.setTag(0);
		
		wallet = AVUser.getCurrentUser().getDouble("credits");
		txv_wallet.setText(String.valueOf(wallet));
		txv_sendto.setText(user.getString("nickname"));

	}

	@Override
	protected void setViews() {

	}

	@Override
	protected void initEvents() {
		layout_alert.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (layout_alert.getVisibility() == View.VISIBLE)
					layout_alert.setVisibility(View.GONE);
			}
		});
		spn_contacts.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				spn_contacts.setTag(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});

		edt_giftnum.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				try {
					int price = madpter.getItem(itemgiftindex).getInt("price");
					int num = Integer.parseInt(s.toString());
					String txt = String.valueOf(price * num);
					txv_giftprice.setText(txt);
				} catch (Exception e) {
				}

			}
		});
		btn_bar_righ.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				if(userlist == null || userlist.size() == 0)
//				{
//					showToast("请选择好友");
//					return;
//				}
				String numstr = edt_giftnum.getText().toString();
				if(TextUtils.isEmpty(numstr)){
					showToast("请输入数量");
					return;
				}
				
				AVObject gift = madpter.getItem(itemgiftindex);
//				AVUser user = userlist.get((Integer)spn_contacts.getTag());
				String message = edt_message.getText().toString().trim();
				final  double price = gift.getDouble("price");

				
				try {
					final int num = Integer.parseInt(numstr);
					if(wallet - price * num <0)
					{
						showToast("金币不足");
						return;
					}
					createWiatDialog("正在发送");
					ALUserEngine.defauleEngine().sendGift(gift, user, num,message, new CallBack() {
						
						@Override
						public void done(Object object, AVException avexception) {
							cancleWaitDialog();
                              if(avexception == null){
                            	  showToast("发送礼物成功");
                            	  wallet -= price * num;
                            	  txv_wallet.setText(String.valueOf(wallet));
                            	  closeAlert();
                              }else{
                            	  showToast("发送礼物失败");
                            	  avexception.printStackTrace();
                              }					
						}
					});
//					if(!TextUtils.isEmpty(message))
//					ALUserEngine.defauleEngine().leaveAMesage(message, user, new CallBack() {
//						
//						@Override
//						public void done(Object object, AVException avexception) {
//							if(avexception != null)
//								avexception.printStackTrace();
//						}
//					});

				} catch (Exception e) {
					e.printStackTrace();
 				}
				 
				
			}
		});
	}
    private void closeAlert(){
		layout_alert.setVisibility(View.GONE);
		imbtn_bar_left
				.setImageResource(R.drawable.ic_leftback_arrow);
		btn_bar_righ.setVisibility(View.INVISIBLE);
    }
	private void uploadGiftlist() {
		ALUserEngine.defauleEngine().getGifts(false, new CallBack() {

			@Override
			public void done(Object object, AVException avexception) {
				if (avexception == null) {
					List<AVObject> list = (List<AVObject>) object;
					if (list == null || list.size() == 0) {
						showToast("没有礼物");
						return;
					}
					madpter = new GiftAdpter(SendGiftActivity.this, list);
					gridview.setAdapter(madpter);

				} else {
					avexception.printStackTrace();
					showToast("获取礼物列表失败");
				}
			}
		});
	}

	private void uploadUserList() {

		ALUserEngine.defauleEngine().getFolloweeList(AVUser.getCurrentUser(),
				100, 0, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {

						MLog.i(TAG, "uploadUserList avexception:" + avexception
								+ "  object:" + object);

						if (avexception == null) {
							HashMap<String, List> map = (HashMap<String, List>) object;
							if (map == null) {
								return;
							}
							List<AVUser> data = map.get("followees");
							if (data == null || data.size() == 0) {
								return;
							}
							userlist = data;
							List<String> strs = new ArrayList<String>();
							for (int i = 0; i < data.size(); i++) {
								strs.add(data.get(i).getString("nickname"));
							}
							ArrayAdapter<String> adpter = new ArrayAdapter<String>(
									SendGiftActivity.this,
									android.R.layout.simple_spinner_item, strs);
							// 设置下拉列表的风格
							adpter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							spn_contacts.setAdapter(adpter);
						     for (int i = 0; i < data.size(); i++) {
								if(user.getObjectId().equals(data.get(i).getObjectId())){
									spn_contacts.setSelection(i);
									spn_contacts.setTag(i);
									return;
								}
							}
						} else {
							avexception.printStackTrace();
						}

					}
				});
	}

	
	@Override
	public void onBackPressed() {
		if (layout_alert.getVisibility() == View.VISIBLE) {
			closeAlert();
			return;
		}
		super.onBackPressed();

	}

	class GiftAdpter extends BaseAdapter {
		// int[] ress =
		// {R.drawable.ic_gift1,R.drawable.ic_gift2,R.drawable.ic_gift3,R.drawable.ic_gift4,R.drawable.ic_gift5,R.drawable.ic_gift6,R.drawable.ic_gift7,
		// R.drawable.ic_gift8,R.drawable.ic_gift9,R.drawable.ic_gift10,R.drawable.ic_gift11,R.drawable.ic_gift12
		// };
		private List<AVObject> giftlist = null;

		@Override
		public int getCount() {
			return giftlist.size();
		}

		@Override
		public AVObject getItem(int position) {
			return giftlist.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		public GiftAdpter(Context context, List<AVObject> giftlist) {
			this.giftlist = giftlist;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			AVObject giftobj = giftlist.get(position);
			final String imageurl = giftobj.getString("imageURL");
			final String name = giftobj.getString("name");
			final double price = giftobj.getDouble("price");

			View view = LayoutInflater.from(SendGiftActivity.this).inflate(
					R.layout.adpter_sendgift, null);
			ImageView imageviw = (ImageView) view.findViewById(R.id.imageview);
			TextView txv_name = (TextView) view.findViewById(R.id.txv_name);
			TextView txv_price = (TextView) view.findViewById(R.id.txv_price);

			aq.id(imageviw).image(imageurl, true, true);
			txv_name.setText(name);
			txv_price.setText(String.valueOf(price));

			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (layout_alert.getVisibility() == View.VISIBLE)
						return;
					layout_alert.setVisibility(View.VISIBLE);
				     edt_giftnum.setText("1");
				     edt_message.setText("");
					
					aq.id(imageview_alert).image(imageurl, true, true);
					txv_giftname.setText(name);
					txv_giftprice.setText(String.valueOf(price));

					imbtn_bar_left
							.setImageResource(R.drawable.btn_bar_leftbtn2);
					btn_bar_righ.setVisibility(View.VISIBLE);

					itemgiftindex = position;
				}
			});
			return view;
		}

	}

}
